package per.hnvcam.searchext.data.dao.impl;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import per.hnvcam.searchext.data.dao.StatisticDAO;
import per.hnvcam.searchext.data.model.Condition;
import per.hnvcam.searchext.data.model.Rule;
import per.hnvcam.searchext.data.model.Statistic;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: camhoang
 * Date: 3/4/12
 * Time: 10:44 PM
 * To change this template use File | Settings | File Templates.
 */
@Service("StatisticDAO")
public class StatisticDAOImpl extends BaseDAOImpl implements StatisticDAO {

   @Autowired
   @Qualifier("sessionFactory")
   private SessionFactory sessionFactory;

   @Override
   public List findAllStatistic() {
      return getHibernateTemplate().find("from Statistic");
   }

   @Override
   public Statistic getLastStatistic() {
      Statistic result = null;
      List list = getRecentStatistic(1);
      if (list != null && list.size() > 0) {
         result = (Statistic) list.get(0);
      }
      return result;
   }

   @Override
   public List getRecentStatistic(int count) {
      Session session = sessionFactory.openSession();
      Query query = session.createQuery("select stats from Statistic as stats order by stats.createdDate desc");
      query.setMaxResults(count);
      return query.list();
   }

   @Override
   public void save(Statistic statistic) {
      getHibernateTemplate().save(statistic);
   }

   @Override
   public void removeAllStatistic() {
      Session session = sessionFactory.openSession();
      Transaction tx = null;
      try {
         tx = session.beginTransaction();

         Query query = session.createQuery("delete s from Statistic as s");
         query.executeUpdate();

         tx.commit();
      } catch (Exception e) {
         if (tx != null) {
            tx.rollback();
         }
      } finally {
         session.close();
      }
   }
}
